package gui;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;


public final class MainPanel extends JPanel {
    private final HashMap<Class<? extends SubPanel>, SubPanel> subPanelCache = new HashMap<>();
    private JFrame parentJFrame;
    private int comCount = 0;

    public MainPanel(JFrame frame) {
        this.parentJFrame = frame;
        setLayout(null);
    }

    public void addSubPanel(String iconFileName, String subPanelName, String subPanelTitle, Class<? extends SubPanel> subPanelClass) {
        //选用图片大小为128*128 按钮大小设置为140*140
        ImageIcon imageIcon = new ImageIcon(iconFileName);
        JButton btn = new JButton(imageIcon);
        JLabel label = new JLabel(subPanelName);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        btn.addActionListener(e -> {
            System.out.println("界面切换到" + subPanelName);
            parentJFrame.setContentPane(getCachePanel(subPanelClass));
            parentJFrame.setTitle(subPanelTitle);
        });
        //小于3说明在第一行
        if (comCount < 3) {
            int i = comCount;
            btn.setBounds((140 * i) + (146 * (i + 1)), 106, 140, 140);
            label.setBounds((140 * i) + (146 * (i + 1)) + 140 / 3, 106 + 140 + 5, 100, 20);
        }
        //第二行
        else if (comCount < 6) {
            int i = comCount - 3;
            btn.setBounds((140 * i) + (146 * (i + 1)), 106 * 2 + 140, 140, 140);
            label.setBounds((140 * i) + (146 * (i + 1)) + 140 / 3, 106 * 2 + 140 * 2 + 5, 100, 20);
        }
        //容器满了
        else {
            return;
        }
        add(btn);
        add(label);
        comCount++;
    }

    public SubPanel getCachePanel(Class<? extends SubPanel> type) {
        if (subPanelCache.containsKey(type)) {
            return subPanelCache.get(type);
        }

        try {
            SubPanel instance = type.newInstance();
            subPanelCache.put(type, instance);
            return instance;
        } catch (Exception e) {
            System.out.println("创建" + type.getSimpleName() + "实例失败");
            e.printStackTrace();
        }

        return null;
    }

}
